#include "stream/impl/rocksdb/meta/Size.h"

#include <iostream>

#include "stream/impl/rocksdb/Rocksdb.h"
#include "stream/impl/rocksdb/Table.h"


static const char * KeySize = "size";

namespace stream {
namespace impl {
namespace rocksdb {
namespace meta {

Size::Size(std::shared_ptr<Rocksdb> db, size_t v)
: stream::meta::Size(v)
, _db(db)
{
}
Size::~Size(){
}

static size_t fromString(const std::string & size){
	//TODO:exception 
	return std::stoull(size);
}
static std::string toString(const size_t size){
	return std::to_string(size);
}

bool Size::load(){
	assert(_db->isOpened());
	std::string size;
	auto s = _db->get(KeySize, size);
	if(s.ok()){
		std::cout << "size from db" << std::endl;
		size_t sz = fromString(size);
		this->set(sz);
		return true;
	}
	else if(s.IsNotFound()){
		std::cout << "size not found in db" << std::endl;
		this->set(0);
		return true;
	}
	else{
		std::cerr << "ERROR:get size from db failed:" << s.ToString() << std::endl;
		this->set(0);
		return false;
	}
}
bool Size::store(){
	assert(_db->isOpened());

	auto s = _db->put(KeySize, toString(get()));
	if(s.ok()){
		return true;
	}
	std::cerr << "ERROR: store to db failed" << s.ToString() << std::endl;
	return false;
}

}//end namespace meta
}//end namespace rocksdb
}//end namespace impl
}//end namespace stream
